﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Lenovo.CFI.BLL;
using Lenovo.CFI.BLL.DicBll;
using Lenovo.CFI.BLL.DicMgr;
using Lenovo.CFI.Common;
using Lenovo.CFI.Common.Dic;
using Lenovo.CFI.Web.Helper;

namespace Lenovo.CFI.Web.VP
{
    public partial class TrackingList : System.Web.UI.UserControl
    {
        IdeaBl ideaBl = new IdeaBl();

        string executor = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            executor = UserHelper.UserName;

            if (!IsPostBack)
            {
                TopicBl topicBl = new TopicBl();
                List<Topic> topics = topicBl.GetTopic();
                topics = topics.FindAll(t => t.Status == TopicStatus.Suggestion || t.Status == TopicStatus.Execution || t.Status == TopicStatus.Closed);

                this.DdlTopic.DataSource = topics;
                this.DdlTopic.DataTextField = "Title";
                this.DdlTopic.DataValueField = "ID";
                this.DdlTopic.DataBind();

                if (topics.Count > 0)
                {
                    selectedTopic = topics[0];
                    ViewState["topicid"] = selectedTopic.ID;
                    ViewState["status"] = -1;

                    this.BindData();
                }

                BindHelper.BindNextAction(this.DdlOtherBuNextAction, "Select...", "-1", null, false);

                MessageHelper.Prepare(this.Page);
            }
        }

        protected void DdlTopic_SelectedIndexChanged(object sender, EventArgs e)
        {
            ViewState["topicid"] = Convert.ToInt32(this.DdlTopic.SelectedValue);

            this.BindData();
        }

        protected void DdlEStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            ViewState["status"] = Convert.ToInt32(this.DdlEStatus.SelectedValue);

            this.BindData();
        }


        Topic selectedTopic = null;
        Dictionary<int, Idea> ideasDic = null;
        private void BindData()
        {
            int topicID = (int)ViewState["topicid"];

            if (selectedTopic == null) selectedTopic = new TopicBl().GetTopicByID(topicID);

            List<string> types = new TopicBl().GetDcTypes(UserHelper.UserName, selectedTopic.ID);

            List<IdeaReview> reviews = new ReviewBl().GetReviewForExecutor(topicID, UserHelper.UserName);

            int status = (int)ViewState["status"];
            if (status != -1)
            {
                reviews = reviews.FindAll(r => r.ActionExecutor == executor && r.ActionStatus == (ExecutionStatus)status ||
                        r.IpExecutor == executor && r.IpStatus == (ExecutionStatus)status);
            }

            ideasDic = new Dictionary<int, Idea>();
            foreach (Idea idea in new IdeaBl().GetIdeaByReviews(reviews)) ideasDic.Add(idea.ID, idea);

            this.GvList.DataSource = reviews;
            this.GvList.DataBind();
        }


        protected void GvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // 设置行号
                ((Literal)(e.Row.FindControl("LtrNo"))).Text = String.Format("{0}", e.Row.DataItemIndex + 1);
                    
                IdeaReview review = (IdeaReview)e.Row.DataItem;
                Idea idea = ideasDic[review.IdeaID];

                ((Literal)e.Row.FindControl("LtrTitle")).Text = String.Format(@"<a href=""{0}"" target=""_blank"">{1}</a>",
                    UrlHelper.GenerateUrl("ideadetail", "id", idea.ID.ToString()), idea.Title);
                ((Literal)e.Row.FindControl("LtrOwner")).Text = idea.Owner;
                ((Literal)e.Row.FindControl("LtrType")).Text = IdeaTypeDicMgr.GetByCode(review.ReviewType).Title;
                ((Literal)e.Row.FindControl("LtrNextAction")).Text = review.NextAction == null ? "" : NextActionDicMgr.GetByCode(review.NextAction).Title;
                ((Literal)e.Row.FindControl("LtrNextIP")).Text = review.NextIP.HasValue ? (review.NextIP.Value ? "Y" : "N") : "";
                
                string status = null;
                if (review.ActionExecutor == executor && review.IpExecutor == executor)
                {
                    status = review.ActionStatusText + " " + review.IpStatusText;
                }
                else if (review.ActionExecutor == executor)
                {
                    status = review.ActionStatusText;
                }
                else if (review.IpExecutor == executor)
                {
                    status = review.IpStatusText;
                }

                ((Literal)e.Row.FindControl("LtrEStatus")).Text = status;

                if (idea.Status == IdeaStatus.Execution)
                {
                    ((ImageButton)e.Row.FindControl("BtnEdit")).Visible = true;
                }
                else
                {
                    ((ImageButton)e.Row.FindControl("BtnEdit")).Visible = false;
                }
            }
        }

        protected void GvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "OpenEdit")
            {
                int id = Convert.ToInt32(e.CommandArgument);
                ViewState["ReviewID"] = id;

                IdeaReview review = new ReviewBl().GetReviewByID(id);
                Idea idea = new IdeaBl().GetIdeaById(review.IdeaID);

                if (review.ActionExecutor == executor)
                {
                    this.PhAction.Visible = true; ViewState["action"] = true;

                    if (review.NextAction == NextAction.GROUPC || review.NextAction == NextAction.CPROJECT)
                    {
                        this.DivProjectName.Visible = true;
                        this.DivProjectTime.Visible = true;
                        this.DivOtherBuNextAction.Visible = false;

                        this.LblProjectName.Text = "Project Name:";
                        this.LblProjectTime.Text = "Kick off Time:";
                        this.TxtProjectName.Text = review.ProjectName;
                        this.DpProjectTime.Value = review.ProjectTime.HasValue ? review.ProjectTime.Value.ToString("yyyy-MM-dd") : "";
                    }
                    else if (review.NextAction == NextAction.PRODUCT || review.NextAction == NextAction.JUSTDOIT)
                    {
                        this.DivProjectName.Visible = true;
                        this.DivProjectTime.Visible = true;
                        this.DivOtherBuNextAction.Visible = false;

                        this.LblProjectName.Text = "Product Name:";
                        this.LblProjectTime.Text = "Load Time:";
                        this.TxtProjectName.Text = review.ProjectName;
                        this.DpProjectTime.Value = review.ProjectTime.HasValue ? review.ProjectTime.Value.ToString("yyyy-MM-dd") : "";
                    }
                    if (review.NextAction == NextAction.OTHERBU)
                    {
                        this.DivProjectName.Visible = false;
                        this.DivProjectTime.Visible = false;
                        this.DivOtherBuNextAction.Visible = true;

                        this.DdlOtherBuNextAction.ClearSelection();
                        if (review.OtherBuNextAction != null)
                        {
                            ListItem item = this.DdlOtherBuNextAction.Items.FindByValue((review.OtherBuNextAction).ToString());
                            item.Selected = true;
                        }
                    }

                    this.TxtActionComment.Text = review.ActionComment;

                    this.DdlProjectStatus.ClearSelection();
                    if (review.ActionStatus != ExecutionStatus.None)
                    {
                        ListItem item = this.DdlProjectStatus.Items.FindByValue(((int)review.ActionStatus).ToString());
                        item.Selected = true;
                    }
                }
                else
                {
                    this.PhAction.Visible = false; ViewState["action"] = false;
                }


                if (review.IpExecutor == executor)
                {
                    this.PhIP.Visible = true; ViewState["ip"] = true;

                    this.TxtIPNo.Text = review.IpNo;

                    this.TxtIPComment.Text = review.IpComment;

                    this.DdlIPStatus.ClearSelection();
                    if (review.IpStatus != ExecutionStatus.None)
                    {
                        ListItem item = this.DdlIPStatus.Items.FindByValue(((int)review.IpStatus).ToString());
                        item.Selected = true;
                    }
                }
                else
                {
                    this.PhIP.Visible = false; ViewState["ip"] = false;
                }

                this.MpeExecution.Show();
            }
        }

        protected void GvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.GvList.PageIndex = e.NewPageIndex;
            this.BindData();
        }


        protected void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                ReviewBl reviewBl = new ReviewBl();
                if ((bool)ViewState["action"])
                {
                    reviewBl.ExecuteAction((int)ViewState["ReviewID"],
                        (ExecutionStatus)Convert.ToInt32(this.DdlProjectStatus.SelectedValue),
                        this.TxtProjectName.Text, this.DpProjectTime.Date,
                        this.DdlOtherBuNextAction.SelectedIndex == 0 ? null : this.DdlOtherBuNextAction.SelectedValue,
                        this.TxtActionComment.Text.Trim());
                }
                if ((bool)ViewState["ip"])
                {
                    reviewBl.ExecuteIP((int)ViewState["ReviewID"],
                        (ExecutionStatus)Convert.ToInt32(this.DdlIPStatus.SelectedValue),
                        this.TxtIPNo.Text.Trim(),
                        this.TxtActionComment.Text.Trim());
                }

                MessageHelper.RegShowJSAjax(this.BtnSave, "Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnSave, ex.Message, this.Page);
            }
            catch (Exception ex)            // Ajax无法使用默认异常处理程序处理异常
            {
                ErrorHelper.ExceptionHanderForAjax(ex, this.BtnSave, this.Page);
            }

            this.BindData();
        }
    }
}